//
//  OPHelperAccountViewController.m
//  OnePiece
//
//  Created by lanou on 15/10/31.
//  Copyright © 2015年 wsy. All rights reserved.
//

#import "OPHelperAccountViewController.h"
#import "OPHelperAccountCell.h"
#import "OPHelperAccountHeaderView.h"
#import "OPHelperAccountWriteViewController.h"
#import "FMDatabase.h"
#import "OPHelperAccountModel.h"
#import "OPDataPickerViewController.h"


@interface OPHelperAccountViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *imageView;
@property (nonatomic, strong) OPHelperAccountHeaderView *headerView;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) FMDatabase *dataBase;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, assign) int totalNum;
@property (nonatomic, strong) NSString *date;
@end


@implementation OPHelperAccountViewController

- (NSMutableArray *)dataSourceArray{
    if (_dataSourceArray == nil) {
        self.dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.945 green:0.458 blue:0.299 alpha:1.000];
    _whiteView = [[UIView alloc]initWithFrame:CGRectMake(10, 60, SCREEN_WIDTH - 20, 4)];
    _whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_whiteView];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(10, 64, SCREEN_WIDTH - 20, SCREEN_HEIGHT - 64)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    [_tableView registerClass:[OPHelperAccountCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    
    UIImageView *bottomView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 20, 10)];
    bottomView.image = [UIImage imageNamed:@"zyc161634202540.jpg"];
    _tableView.tableFooterView = bottomView;

    
    _headerView = [[OPHelperAccountHeaderView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 50)];
    _headerView.backgroundColor = [UIColor whiteColor];
    [_headerView.iconView addTarget:self action:@selector(didClickCanlender) forControlEvents:(UIControlEventTouchUpInside)];
    [_headerView.backBtn addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_headerView];
    
    _imageView = [[UILabel alloc]init];
    _imageView.backgroundColor = [UIColor colorWithRed:0.762 green:0.660 blue:1.000 alpha:1.000];
    _imageView.frame = CGRectMake(0, _headerView.frame.size.height - 5, SCREEN_WIDTH, 5);
    [_headerView addSubview:_imageView];
    
    _addBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_addBtn setImage:[UIImage imageNamed:@"zyciconfont-add-round (2)"] forState:(UIControlStateNormal)];
    _addBtn.frame = CGRectMake(20, SCREEN_HEIGHT - 100, 40, 40);
    [_addBtn addTarget:self action:@selector(didClickAddBtn) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_addBtn];

    
    
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY年MM月dd日"];
    self.date = [dateformatter stringFromDate:date];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableArray *arr = [user objectForKey:_date];
    for (NSDictionary *dic in arr) {
        OPHelperAccountModel *m = [[OPHelperAccountModel alloc]init];
        m.money = dic[@"money"];
        m.icon = dic[@"typeImg"];
        m.content = dic[@"typeCh"];
        [self.dataSourceArray addObject:m];
        self.totalNum += m.money.intValue;
    }
    [self.tableView reloadData];
    self.headerView.money.text = [NSString stringWithFormat:@"合计：%d元",self.totalNum];
}

- (void)longPress:(UITapGestureRecognizer *)tap
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定要删除吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil];
    UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action)
    {
        [self deleteCellWithCell:(OPHelperAccountCell *)tap.view];
    }];
    [alert addAction:act1];
    [alert addAction:act2];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)deleteCellWithCell:(OPHelperAccountCell *)cell
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:[user objectForKey:_date]];
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    [user setObject:arr forKey:_date];
    [arr removeObjectAtIndex:index.row];
    [self.dataSourceArray removeObjectAtIndex:index.row];
    [self.tableView reloadData];
    self.headerView.money.text = [NSString stringWithFormat:@"合计：%d元",self.totalNum];
}


- (void)dataBaseReloadWithData:(NSString *)str
{
    self.totalNum = 0;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableArray *arr = [user objectForKey:str];
    [self.dataSourceArray removeAllObjects];
    for (NSDictionary *dic in arr) {
        OPHelperAccountModel *m = [[OPHelperAccountModel alloc]init];
        m.money = dic[@"money"];
        m.icon = dic[@"typeImg"];
        m.content = dic[@"typeCh"];
        [self.dataSourceArray addObject:m];
        self.totalNum += m.money.intValue;
    }
    [self.tableView reloadData];
    self.headerView.money.text = [NSString stringWithFormat:@"合计：%d元",self.totalNum];

}

- (void)didClickCanlender
{
    OPDataPickerViewController *dataVC = [[OPDataPickerViewController alloc]init];
    dataVC.picker.datePickerMode = UIDatePickerModeDate;
    [self presentViewController:dataVC animated:YES completion:^{
        
        dataVC.dataBlock = ^(NSString *string)
        {
            NSString *str = [string substringWithRange:NSMakeRange(0, 11)];
            _headerView.contentLabel.text = str;
            [self dataBaseReloadWithData:str];
            self.date = str;
        };
    }];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didClickAddBtn
{
    OPHelperAccountWriteViewController *writeVC = [[OPHelperAccountWriteViewController alloc]init];
    writeVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    writeVC.freshBlock = ^(NSString *str)
    {
        [self dataBaseReloadWithData:str];
    };
    [self presentViewController:writeVC animated:YES completion:nil];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OPHelperAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    OPHelperAccountModel *m = self.dataSourceArray[indexPath.row];
    [cell configuraDataWithModel:m];
    
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    press.minimumPressDuration = 1.0;
    [cell addGestureRecognizer:press];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArray.count;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0) {
        _whiteView.frame = CGRectMake(10, 60, SCREEN_WIDTH - 20, 4 - scrollView.contentOffset.y);
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
